package com.hxm.appGenealogy.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.hxm.appGenealogy.entity.ResponDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@CrossOrigin
@RestController
@RequestMapping("add/file")
public class FileController {


    @Autowired
    private OSS ossClient;

    @Value("${huangye.aliyun.httpPrefile}")
    private String httpPrefile;

    @Value("${huangye.aliyun.bucketName}")
    private String bucketName;

    @PostMapping("/uploadfile")
    public ResponDataVo file(@RequestBody MultipartFile multipartFile) {
        //生产随机数;
        //String filename = getRandomString(20);
        String filename1 = multipartFile.getResource().getFilename() + UUID.randomUUID();
        try {
            ossClient.putObject(bucketName, filename1, new ByteArrayInputStream(multipartFile.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponDataVo(true, "success", httpPrefile + "/" + filename1);
    }

    //生产随机数,用于照片的名称;
    public static String getRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSeqwewqewqs" +
                "dsadsadasdasJPFJ0OQWU0-QWID0-QWIDSAMD;LSKAD;LASKDL;KSAL;DKASL;DKALS;KDALS;" +
                "acascasrqweqweqwewqTUVWXY45456465465hikhklhksajdl;askdl;askdl;askdl;askdl;askl;daksl;dksa" +
                "dksakdl;askdl;askdl;askdl;askdl;askl;dasdkl;sakdl;askdl;askdl;askd;'aDk[pqwiepwqie[pq  dkalpfh0oq['qshDCNWEIOQGFOWIQ" +
                "QWOPEUPQ-WI]E" +
                "[pqkdqwp[dmqwlndqwoyeopqwip['wmdqwphdoiqwyeioqwudposmxcp'HQFDOIWQEUJQWPODJQWPDNOIQWHRQ qwjepqwndioqwhdoqweudqw" +
                "dk[qpwdip[wqkldjhkjhkjhjkhZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }


    @PostMapping("uploadvideo")
    public ResponDataVo uploadVideo(@RequestBody MultipartFile multipartVideo) {
        String filename = multipartVideo.getResource().getFilename();
        //设置请求头的信息;
        try {
            PutObjectResult putObjectResult = ossClient.putObject(bucketName, filename, multipartVideo.getResource().getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        String url = httpPrefile + "/" + filename;
        return new ResponDataVo(url);
    }


}
